<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of account
 *
 * @author b4by
 */
class account extends MY_Controller {

	protected $_attributeObjects;
	protected $_attributes;

	public function getAttributeObjects() {
		if (!$this->_attributeObjects) {
			$this->_attributeObjects = $this->getAttributes();
			array_to_object($this->_attributeObjects);
		}
		return $this->_attributeObjects;
	}

	public function getAttributes() {
		if (!$this->_attributes) {
			$this->load->model('model_attribute');
			$this->_attributes = $this->model_attribute->get_list_hash($this->user_lang->id, array(
				'order' => array('index', 'asc'),
			));
		}
		return $this->_attributes;
	}
	
	function __construct() {
		parent::__construct();
	}

	public function index() {
		$this->load_view();
	}

	public function register() {
		$this->load->helper('form');
		$this->load->library('form_validation');

		$this->form_validation->set_rules('username', 'lang:username', 'required|min_length[5]|max_length[50]');
		$this->form_validation->set_rules('password', 'lang:password', 'required|min_length[5]|max_length[30]');
		$this->form_validation->set_rules('password1', 'lang:password_confirm', 'required|matches[password]');
		$this->form_validation->set_rules('mobile', 'lang:mobile', 'required|min_length[8]|max_length[20]');
		$this->form_validation->set_rules('fullname', 'lang:fullname', 'min_length[8]|max_length[100]');
		$this->form_validation->set_rules('address', 'lang:address', 'min_length[8]');
		$this->form_validation->set_rules('email', 'lang:email', 'required|valid_email|callback__check_email');
		$this->form_validation->set_rules('agree', 'lang:agree_terms', 'required|callback__check_agree_terms');
//		$this->form_validation->set_rules('gender','lang:gender','callback__check_gender');


		if ($this->form_is_valid()) {
			$data = request_filter(array('username', 'password', 'mobile', 'email', 'address'));
			$data['password'] = md5($data['password']);
			$data['active'] = 1;
			$this->model_user->create($data);

			echo json_encode(array(
				'state' => 'success',
				'message' => lang('registration_success'),
			));
		} else {
			echo json_encode(array(
				'state' => 'error',
				'errors' => $this->data['errors']
			));
		}
	}

	public function _check_email($email) {
		$info = $this->model_user->get_info_rule(array(
			'email' => $email,
		));
		if ($info === FALSE)
			return TRUE;
		$this->form_validation->set_message(__FUNCTION__, lang('email_used'));
		return FALSE;
	}

	public function _check_agree_terms($value) {
		if ($value == 1)
			return TRUE;
		$this->form_validation->set_message(__FUNCTION__, lang('agree_terms_notify'));
		return FALSE;
	}

	public function login() {
		$this->load->helper('form');
		$this->load->library('form_validation');

		$this->form_validation->set_rules('email', 'lang:email', 'required');
		$this->form_validation->set_rules('password', 'lang:password', 'required|callback__check_login');

		if ($this->form_is_valid()) {
			echo json_encode(array(
				'state' => 'success',
				'user' => '',
			));
		} else {
			$data = array(
				'state' => 'error',
				'errors' => $this->data['errors'],
			);
			echo json_encode($data);
		}
	}

	public function _check_login($value) {
		if (user_login($this->input->post('username'), $this->input->post('password'), $this->input->post('remember')))
			return TRUE;
		$this->form_validation->set_message(__FUNCTION__, lang('login_fail'));
		return FALSE;
	}

	/**
	 * 
	 */
	public function fb_login() {

		$ref = request('ref');

		if ($ref == '')
			$ref = url_create('site');

		if (preg_match('/' . addcslashes(url_create('site', 'account', 'fb_login'), '/.\\*+[])(|?^') . '/i', $ref) != 0)
			$ref = url_create('site');

		if ($this->isUserLogin())
			redirect($ref);

		$this->load->library('facebook');
		$this->load->model('model_user');

		$code = request('code');

		if (strlen($code) == 0) {
			redirect($this->facebook->getLoginUrl(array(
						'scope' => 'email,user_about_me'
			)));
		}
		$graph_url = "https://graph.facebook.com/me?access_token="
				. $this->facebook->getAccessToken();

		$user = json_decode(file_get_contents($graph_url));

		$fb_userId = @$user->id;

		if ($fb_userId == 0) {
                        show_error(lang('Facebook not authentication'));
			exit;
		}
		$info = $this->model_user->get_info_rule(array('fb_id' => $fb_userId));

		if ($info !== false) {
			$this->model_user->update($info->id, array(
				'username' => $user->username,
				'fullname' => $user->name,
			));
			$this->session->set_userdata('user_id', $info->id);
			redirect($ref);
		}

		$user_id = $this->model_user->create(array(
			'email' => $user->email,
			'username' => $user->username,
			'fb_id' => $fb_userId,
			'active' => 1,
			'group_id' => $this->siteConfig->default_user_group,
			'fullname' => $user->name,
			'join_date' => now()
		));

		$this->session->set_userdata('user_id', $user_id);

		redirect($ref);
	}

	public function logout() {

		$this->session->set_userdata('user_id', $this->siteConfig->guest_id);
		set_cookie('username', '');
		set_cookie('password', '');
		redirect(url_create('site'));
	}

	public function info($id = '') {
		if ($id == '')
			$id = $this->user->id;

		$attributes = $this->getAttributes();
		$user = $this->model_user->get_info($id);
		
		foreach ($user->attributes as $userAttributeId => $row) {			
			if ($attributes[$userAttributeId]->p_id == 0) {
				$attributes[$userAttributeId]->value = $row->value;
			} else {
				switch ($attributes[$attributes[$userAttributeId]->p_id]->value_type) {
					case 1:
						$attributes[$attributes[$userAttributeId]->p_id]->value = $attributes[$userAttributeId]->name;
						break;
					case 2:
						$attributes[$attributes[$userAttributeId]->p_id]->value[] = $attributes[$userAttributeId]->name;
						break;
					case 4: 
						$attributes[$attributes[$userAttributeId]->p_id]->value[] = $attributes[$userAttributeId]->value;
						break;
				}
			}
		}
		foreach ($attributes as &$attribute) {
			if (!isset($attribute->value))
				$attribute->value = '';
		}

		$this->data['attributes'] = $attributes;
		

		$this->data['temp'] = 'account/info';
		$this->load_view();
	}

	public function update() {
		$this->load->model('model_attribute');
		
		$attributeObjects = $this->getAttributeObjects();
		$this->data['attributeObjects'] = $attributeObjects;
		
		$attributes = $this->getAttributes();
		$user = $this->model_user->get_info($this->user->id);
		
		foreach ($user->attributes as $userAttributeId => $row) {			
			if ($attributes[$userAttributeId]->p_id == 0) {
				$attributes[$userAttributeId]->value = $row->value;
			} else {
				switch ($attributes[$attributes[$userAttributeId]->p_id]->value_type) {
					case 1:
						$attributes[$attributes[$userAttributeId]->p_id]->value = $attributes[$userAttributeId]->id;
						break;
					case 2:
						$attributes[$attributes[$userAttributeId]->p_id]->value[] = $attributes[$userAttributeId]->id;
						break;
					case 4: 
						$attributes[$attributes[$userAttributeId]->p_id]->value[] = $attributes[$userAttributeId]->id;
						break;
				}
			}
		}
		foreach ($attributes as &$attribute) {
			if (!isset($attribute->value))
				$attribute->value = '';
		}

		$this->data['attributes'] = $attributes;

		if (isset($_POST['submit'])) {
			$this->load->helper('form');
			$this->load->library('form_validation');
			// Auto set validation rule for attributes
			foreach ($attributeObjects as $attribute) {
				if (strlen($attribute->validation) > 0) {
					$this->form_validation->set_rules('attribute_' . $attribute->id, $attribute->name, $attribute->validation);
				}
			}

			if ($this->form_is_valid()) {

				$this->load->model('model_user_attrib');
				$userAttributes = array();
				foreach ($_POST as $key => $val) {
					if (preg_match('/attribute_(\d+)/i', $key)) {

						$attributeId = preg_replace('/attribute_(\d+)/i', '$1', $key);

						$valueType = $attributeObjects[$attributeId]->value_type;
						switch ($valueType) {
							case 1:
								$userAttributes[] = array(
									'user_id' => $this->user->id,
									'attrib_id' => $val,
									'value'	=> null,
								);
								break;
							case 2:
								foreach ($val as $childAttributeId) {
									$userAttributes[] = array(
										'user_id' => $this->user->id,
										'attrib_id' => $childAttributeId,
										'value'	=> null,
									);
								}
								break;
							default:
								$userAttributes[] = array(
									'user_id' => $this->user->id,
									'attrib_id' => $attributeId,
									'value' => $val,
								);
								break;
						}
					}
				}
				$this->model_user_attrib->primary_key = 'attrib_id';
				$oldUserAttributes = $this->model_user_attrib->get_list_hash(array(
					'select' => 'attrib_id',
					'where' => array('user_id' => $this->user->id),
				));
//				pr($oldUserAttributes);die;
				foreach ($userAttributes as $userAttribute) {
					if (!array_key_exists($userAttribute['attrib_id'], $oldUserAttributes)) {
						$this->model_user_attrib->create($userAttribute);
					}
					else
						$this->model_user_attrib->update_rule(array(
							'user_id' => $this->user->id,
							'attrib_id' => $userAttribute['attrib_id']
								), array('value' => $userAttribute['value']));
				}

				redirect(url_create('site','account','info'));
			} 
//			else {
//				pr($this->data['errors']);
//				die;
//			}
		}


		$this->data['temp'] = 'account/update';
		$this->load_view();
	}

	/**
	 * Upload user's profile image
	 */
	public function upload() {

		$this->load->model('model_file');

		$config = array();
		$config['encrypt_name'] = $this->siteConfig->image_encrypt_name == 1;
		$config['upload_path'] = $this->siteConfig->image_upload_path;
		$config['allowed_types'] = $this->siteConfig->image_types;
		$config['max_size'] = $this->siteConfig->image_max_size;
		$config['max_width'] = $this->siteConfig->image_max_width;
		$config['max_height'] = $this->siteConfig->image_max_height;

		$this->load->library('upload', $config);
		if ($this->upload->do_upload('file')) {
			$upload = $this->upload->data();
			$path = $config['upload_path'] . '/' . $upload['file_name'];

			$resize_config = array(
				'source_image' => $upload['full_path'],
				'maintain_ratio' => TRUE,
				'width' => $this->siteConfig->image_width,
				'height' => $this->siteConfig->image_height,
			);
			$size = getimagesize($upload['full_path']);
			if ($size[0] > $this->siteConfig->image_width) {
				$this->load->library('image_lib', $resize_config);
				$this->image_lib->resize();
			}
			$resize_config['height'] = $this->siteConfig->thumb_height;
			$resize_config['width'] = $this->siteConfig->thumb_width;
			$resize_config['create_thumb'] = TRUE;
			$this->load->library('image_lib', $resize_config, 'image_lib1');
			$this->image_lib1->resize();

			$thumb = preg_replace('/(.+)(\.(' . $this->siteConfig->image_types . '))/i', '$1_thumb$2', $path);

			$id = $this->model_file->create(array(
				'file_name' => $path,
				'orig_name' => $upload['orig_name'],
				'thumb_name' => $thumb,
				'time' => now(),
				'status' => 1,
			));

			$image = $this->model_file->get_info($id);
			$this->user->total_upload++;
			$this->model_user->update($this->user->id, array(
				'avatar_thumb' => $image->thumb_name,
				'avatar' => $image->file_name,
				'avatar_id' => $id,
				'last_upload' => now(),
				'total_upload' => $this->user->total_upload,
			));

			echo json_encode(array(
				'state' => 'success',
				'id' => $id,
				'image' => image_url($path),
				'thumb' => image_url($thumb),
			));
		} else {
			echo json_encode(array(
				'state' => 'error',
				'message' => preg_replace('/<p>([^<]+)<\/p>/i', '$1', $this->upload->display_errors()),
			));
		}
	}

}

?>
